<?php
namespace control;
//管理员后台-出库单
use JetBrains\PhpStorm\NoReturn;

class outStockClass extends adIndexClass
{
	private const title       = '待出库单';
	private const page        = 'outStock';
	private const table       = 'inventory';
	private const tableMx     = 'inventory_detail';
	private const tableRecord = 'inventory_record';
	private const workflow    = ['待出库', '部分出库', '已出库'];
	private const source      = ['生产领料', '销售发货', '采购退货', '配料出库','委外退货','委外领料'];
    private const qualityState  = ['无', '待质检', '已质检'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {

        switch ($fun) {
            default:
                $tr = [
                    'warehouse'          => [
                        'name'  => '{l.outStock.homeSearch.warehouse}',
                        'width' => 200,
                    ],
                    'type' => [
                        'name'  => '{l.outStock.homeSearch.type}',
                        'width' => 200,
                    ],
                    'sourceNo'  => [
                        'name'  => '{l.outStock.homeSearch.sOrderNo}',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'targetId'  => [
                        'name'  => '{l.outStock.homeSearch.target}',
                        'width' => 200,
                    ],
                    'sourceDate'  => [
                        'name'  => '{l.outStock.homeSearch.sDate}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo'         => [
                        'name'  => '{l.outStock.homeSearch.orderNo}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '{l.outStock.homeSearch.state}',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $result = sqlFind("SELECT id, name FROM `warehouse` WHERE coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql());
        $value  = [];
        foreach ($result as $v) {
            $value[$v['id']] = $v['name'];
        }
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('outStock.homeForm.all') => checkbox([
                        "name"    => "warehouse",
                        "value"   => $value,
                        'checked' => '',
                    ]),
                ],
                [
                    L('outStock.homeForm.source') => select(["name" => "source", 'option' => self::source]),
                    L('outStock.homeForm.orderNo')   => text(array("name" => "orderNo")),
                    L('outStock.homeForm.sOrderNo')   => text(array("name" => "sOrderNo")),
                ],
                [
                    L('outStock.homeForm.target')  => selectMultiple(['option' => inStockOtherClass::currentCompany(), 'name' => 'targetId', 'class' => 'width200']),
                    L('outStock.homeForm.sDate') => text(['name' => 'sDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                    L('outStock.homeForm.stateSelect') => select(["name" => "stateSelect", 'option' => self::workflow]).
                        hidden(['name' => 'state', 'value' => '待出库']),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',type:'待出库'})\">导出</span>";
        }
        $tip = componentClass::tipComponent('批量出库需要选择相同业务类型和相同往来单位的单据，如果出库前需要先完成质检，则数据无法带出', '!');
        $button .= <<<EOT
					<span class="spanButton" onclick="batchPutOut()">批量出库</span>$tip
				EOT;
        $button .= "
					<script>
                        function batchPutOut() {
                            var list = $(\"[name='listId[]']:checked\")
                            const arrar = []
                            if(list.length  == 0) {
                                warn('请选择待出库单')
                            }else{
                                list.each(function () {
                                    arrar.push($(this).val())
                                })
                                const url = root + 'control/adIndex.html?cla=outStock&fun=batchPutOut'
                                $.post(url, {ids:JSON.stringify(arrar)}, function (data) {
                                    if (data.warn == 2) {
                                        newIframe('" . L('outStockExec.homeListSearch.detail') . "',data.href)
                                    } else {
                                        warn(data.warn);
                                    }
                                }, 'json');
                            }
                        }
                    </script>
				";
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}



	/*列表页-查询结果*/
	public function homeSearch($workFlow = '待出库'): bool|string
	{
		$notIn  = ['其他出库', '调拨单出库', '拆解单出库', '组装单出库'];
		$where  = " `coid` = '" . self::$coid . "' AND `classify`=0  ";
		$equal = [
			'sourceTable' => match ($this->post('source')) {
				 '盘点单'   => 'inventory_take',
				'生产领料' => 'pick_order',
				'销售发货' => 'sale_send_order',
				'采购退货' => 'purchase_refund_order',
				'配料出库' => 'ingredients_order',
				default    => '',
			},
		];
		$like  = [
			'targetId' => $this->post('targetId'),
			'orderNo'  => $this->post('orderNo'),
			'sourceNo' => $this->post('sOrderNo'),
		];
		$where .= self::timeComparison($this->post('sDate'), field: 'sourceDate');
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('stateSelect')) {
			$where .= " and state = '" . $this->post('stateSelect') . "' ";
		} else {
			$where .= " and state in ('待出库','部分出库') ";
		}
		if ($this->post('warehouse')) {
			$where .= " AND warehouseId in ('" . implode("','", $this->post('warehouse')) . "')";
		} else {
			$where .= self::getWarehouseSql('warehouseId');  //自己管理的仓库
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page                                   = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
		$_SESSION[self::page][$workFlow]['sql'] = $page['sql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url     = root . "control/adIndex.html?cla=" . self::page;
		$isPrint = $this->power(self::page, "print");
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate  = [
				"box"    => [
					"name" => "listId", "value" => $array['id'],
				],
				"detail" => [
					"title" => L('outStock.homeSearch.detail'), "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",
				],
			];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'targetId':
                        $row[] = inStockOtherClass::getCompanyName($array['targetId']);
                        break;
                    case 'sourceDate':
                        $row[] = self::formatDate($array['sourceDate']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = L('outStock.detail.empty');
		} else {
			//菜单
			$data = array(
				"id" => $info['id'],
			);
            $button=[];
            $button[] = [
                "name" => L('outStock.detail.printBarcode'),
                "type" => "弹出层",
                "cla"  => $this->get('cla'),
                "fun"  => "
                
                
                ",
                "post" => ["id" => $info['id']],
            ];
			/*if ($this->power(self::page, "edit") && $info['state'] != '已出库') {
				$button[] = [
					"name" => "出库完成",
					"type" => "弹出层",
					"cla" => $this->get('cla'),
					"fun" => "operate",
					"post" => ["act" => 'commit', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}*/
			$sourceAlias = match ($info['sourceTable']) {
				'inventory_take'        => L('outStock.detail.inventory_take'),
				'pick_order'            => L('outStock.detail.pick_order'),
				'sale_send_order'       => L('outStock.detail.sale_send_order'),
				'purchase_refund_order' => L('outStock.detail.purchase_refund_order'),
				'ingredients_order'     => L('outStock.detail.ingredients_order'),
				default                 => L('outStock.detail.other'),
			};
			$warehouse   = query('warehouse', " id = '$info[warehouseId]' ");
			if ($info['sourceTable']) {
				$obj = query($info['sourceTable'], " id = '{$info['sourceId']}' ");
			} else {
				$obj['orderNo'] = $obj['text'] = $obj['recordDate'] = '';
			}
			$checkAll = $this->checkAll("detailForm", "listId");
			$mxtr[]   = [$checkAll, L('outStock.detail.code'), L('outStock.detail.name'), L('outStock.detail.model'), L('outStock.detail.unit'), L('outStock.detail.orderNum'), L('outStock.detail.num'), L('outStock.detail.batch'), L('outStock.detail.notOut'), '质检状态'];
			$result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            $totalArr = ['orderNum'=>0,'num'=>0];

            $outStockQuality = optionSettingClass::getSettingItem('库存', 'outStockQuality');// 出库前是否需要先完成质检
			foreach ($result['array'] as $array) {
				//列表控件
				$dominate    = [
					"box" => [
						"name" => "listId", "value" => $array['id'],
					],
				];
                // 如果需要质检才能入库
                if($array['quality'] == 1 && $outStockQuality){
                    unset($dominate['box']);
                }
				$material    = query('material', " id = '$array[materialId]'");
				$batch  = inStockClass::getInventoryBatch($array['id'], true);  //查询批次对应数量
				$mxtr[] = [
				    $this->dominate($dominate),
					$material['code'],
					$material['name'],
					$material['model'],
					$array['unit'],
					self::lostZero($array['orderNum'], 'numPrecision'),
					self::lostZero($array['num'], 'numPrecision'),
					$batch,
					$array['orderNum'] - $array['num'],
                    self::qualityState[$array['quality']]
				];
                $totalArr['orderNum'] += $array['orderNum'];
                $totalArr['num'] += $array['num'];
			}
            $total_tr = [
                5 => self::lostZero($totalArr['orderNum'], 'numPrecision'),
                6 => self::lostZero($totalArr['num'], 'numPrecision'),
                8 => self::formattingFigure($totalArr['orderNum'] - $totalArr['num'], 'numPrecision'),
            ];
			$mxButton = '';
			if (in_array($info['state'], ['待出库', '部分出库'])) {
                $tip = $outStockQuality ? componentClass::tipComponent("出库前需要先完成质检，如果状态为待质检，则不能选择出库") : '';
				$mxButton .= <<<EOT
					<span class="smallButton" onclick="batchPutOutStock('{$info['id']}')">批量出库</span>$tip
				EOT;
                $mxButton .= "
					<script>
                        function batchPutOutStock(targetId) {
                            var list = $(\"[name='listId[]']:checked\")
                            var str = ''
                            const arrar = []
                            if(list.length  == 0) {
                                warn('请选择物料')
                            }else{
                                list.each(function () {
                                    arrar.push($(this).val())
                                })
                                str = arrar.join('/')
                                newIframe('" . L('outStockExec.homeListSearch.detail') . "',root +'control/adIndex.html?cla=outStockExec&fun=edit&targetId='+targetId+'&ids='+str)
                            }
                        }
                    </script>
				";
			}

			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				[
					[
                        L('outStock.detail.source') => $sourceAlias,
                        L('outStock.detail.orderNo') => $obj['orderNo'],
                        L('outStock.detail.target') => inStockOtherClass::getCompanyName($info['targetId']),
                        L('outStock.detail.sOrderNo') => self::formatDate($obj['recordDate'] ?? ''),
					],
					[
                        L('outStock.detail.outNo') => $info['orderNo'],
                        L('outStock.detail.warehouse')     => $warehouse['name'],
                        L('outStock.detail.state')     => $info['state'],
                        L('outStock.detail.commitTime') => $info['commitTime'],
					],
					[

                        L('outStock.detail.confirmTime') => $info['confirmTime'],
                        L('outStock.detail.storekeeper')       => componentClass::showSelector($warehouse['selector']),
					],
                    [

                        L('outStock.detail.sText') => $obj['text'] ? pre($obj['text']) : '',
                    ],
				]
			]);
            $data['html'] .= $this->detailList([
                'title' => L('outStock.detail.sendDetail'),
                'button' => $mxButton,
                'html' => "<form name='detailForm'>".$this->listTable(array('tr' => $mxtr, 'showEmpty' => true, 'showSort' => true, 'total' => $total_tr))."</form>",
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

    // 批量出库组合
    public function batchPutOut()
    {
        $ids    = $this->post('ids') ? json_decode($_POST['ids'],true) : [];
        $first = [];
        $mxId = [];
        foreach ($ids as $k=>$id){
            $info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$id}'");
            if($k===0)$first = $info;
            if($first['targetId'] == $info['targetId'] && $first['type'] == $info['type'] && $info['state'] != '已出库'){
                $result   = find(array('table' => self::tableMx, 'field' => 'id', 'where' => "orderId = '$info[id]' order by list"));
                $mxId = array_merge($mxId,array_column($result['array'],'id'));
            }
        }
        if(count($mxId) > 0) {
            $json['warn'] = 2;
            $json['href'] = root.'control/adIndex.html?cla=outStockExec&fun=edit&targetId='.$first['id'].'&ids='.implode('/',$mxId);
        }else{
            $json['warn'] = '未匹配到数据';
        }
        return json_encode($json, 320);
    }


	// 操作中转
	public function operate(): bool|string
	{
		$act    = $this->post('act') ?? '';
		$id     = $this->post('id') ?? '';
		$pwd    = $word = $height = false; // 需要密码
		$form   = $power = '';
		$append = [];
		switch ($act) {
			case 'batchOut':
				$act      = 'edit';
				$msg      = '批量出库';
				$title    = '是否确认将选中的出库单明细批量出库';
				$function = 'batchOutEdit';
				$word     = true;
				$form     = self::page . 'OperateForm, detailForm';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
				'append'   => $append,
				'height'   => $height,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 生成物流发货单
	 */
	public static function delivery_order($inventory): bool|string
	{
		$info             = query($inventory['sourceTable'], " id = '{$inventory['sourceId']}' ");
		$field            = [
			'id'          => suiji(),
			'coid'        => self::$coid,
			'sourceTable' => 'inventory',
			'sourceId'    => $inventory['id'],
			'khid'        => $info['khid'],
			'manager'     => $info['manager'],
			'contractId'  => $info['contractId'],
			'recordDate'  => $info['recordDate'],
			'limitTime'   => $info['limitTime'],
			'text'        => $info['text'],
			'contactName' => $info['contactName'],
			'contactTel'  => $info['contactTel'],
			'address'     => $info['address'],
			'money'       => $info['money'],
			'isTax'       => $info['isTax'],
			'stid'        => $info['stid'],
			'updateTime'  => date("Y-m-d H:i:s"),
			'time'        => date("Y-m-d H:i:s"),
		];
		$field['orderNo'] = codeTemplateClass::generateCode('deliveryManage', [
			'prefix' => 'XSFH' . date('Ymd', strtotime($field['recordDate'])),
			'table'  => 'delivery_order',
			'field'  => 'orderNo',
			'where'  => " and coid = '" . self::$coid . "'",
		], $field);
		$warn             = static::insert(array(
			'table' => 'delivery_order',
			'field' => $field,
		));
		if ($warn != '新增成功') {
			return '生成物流发货单失败';
		}

		$all = find(array(
			'table' => "inventory_detail as a",
			'field' => "a.*",
			'where' => "a.orderId = '$inventory[id]' and a.coid = '" . self::$coid . "' order by a.list asc",
		));
		foreach ($all['array'] as $array) {
			$sourceTable = query($array['sourceTable'], " id = '{$array['sourceId']}' ");
			$warn        = static::insert(array(
				'table' => 'delivery_order_detail',
				'field' => [
					'id'              => suiji(),
					'coid'            => self::$coid,
					'orderId'         => $field['id'],
					'sourceTable'     => 'inventory_detail',
					'sourceId'        => $array['id'],
					'saleOrderMxId'   => $sourceTable['saleOrderMxId'],
					'khMaterialCode'  => '',
					'khMaterialName'  => '',
					'materialId'      => $array['materialId'],
					'warehouseId'     => $array['warehouseId'],
					'num'             => $array['num'],
					'unit'            => $array['unit'],
					'price'           => $array['price'],
					'taxMoney'        => 0,
					'moneyWithOutTax' => 0,
					'rate'            => $array['rate'],
					'money'           => $array['money'],
				],
			));
			if ($warn != '新增成功') {
				return '生成物流发货明细失败';
			}
		}
		return true;
	}

	/**
	 * 导出
	 */
	public function exportData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
		$workFlow = $this->get('type');
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $sql    = $_SESSION[self::page][$workFlow]['sql'];
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                if ($array['sourceTable']) {
                    $obj = query($array['sourceTable'], " id = '{$array['sourceId']}' ");
                } else {
                    $obj['orderNo'] = '';
                }
                $mx   = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]' order by list"));
                foreach ($mx['array'] as $value) {
                    $column = [];
                    $material    = query('material', " id = '$value[materialId]'");
                    $batch  = inStockClass::getInventoryBatch($value['id'], true);  //查询批次对应数量
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '仓库'=>warehouseClass::getName($array['warehouseId']),
                                '业务类型'=>$array['type'],
                                '源单编号'=>$obj['orderNo'],
                                '往来单位'=> inStockOtherClass::getCompanyName($array['targetId']),
                                '源单日期'=>self::formatDate($array['time']),
                                '出库单号'=> $array['orderNo'],
                                '物料编码'=>$material['code'],
                                '物料名称'=>   $material['name'],
                                '规格型号'=> $material['model'],
                                '单位'=>$value['unit'],
                                '单据数量'=>self::lostZero($value['orderNum'], 'numPrecision'),
                                '已出库数量'=> self::lostZero($value['num'], 'numPrecision'),
                                '批次明细'=>$batch,
                                '剩余未出库数量'=>self::lostZero($value['orderNum'] - $value['num'], 'numPrecision'),
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }

            }
			$text = str_replace(['{{staffName}}'], [$this->control['name']], lang('outStock.exportData.total'));
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, self::title . '-' . $workFlow . ".xlsx");
            exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));

	}

	public function printEdit(): bool|string
	{
		$root    = root;


		$result  = find([
			'table' => self::tableMx,
			'where' => " orderId = '{$this->post('id')}' ",
		]);
		$printNumWord = L('outStock.printEdit.printNum');
		$printWord = L('outStock.printEdit.print');
		$content = '';
		foreach ((array)$result['array'] as $array) {
			//材料信息
			$material     = query('material', "id = '$array[materialId]'");
			$barcode      = $material['barcode'];
			$parameter    = urlencode($barcode);
			$content      .= <<<EOT
                            <li>
                               <div class="qr-content">
                                     <img alt="" src='{$root}pay/wxpay/wxScanPng.php?url=$parameter'>
                                     <div class="qr-content-barcode">$barcode</div>
                                     <div class="qr-content-bottom">{$material['name']},{$material['model']}</div>
                                     <input name='listId[]' type='hidden' value='{$array['materialId']}'>
                               </div>
                               <input class="text qr-num" name='num[]' placeholder='$printNumWord'>
                           </li>
EOT;
		}

		$html = <<<EOT
                <form name="printForm" target="_blank" method="post" action="{$root}control/adIndex.html?cla=materialDetail&fun=printPage">
                <div class="printEditPage">
                      <ul>
                           $content
                      </ul>
                </div>
                <div style='width: 100%;margin-top: 40px;text-align: center;'>
                    <input type='submit' class='button' value='$printWord' ">
                </div>
                </form>

EOT;
		return $this->layer(array("title" => $printWord, "height" => 650, "width" => 900, "html" => $html . inStockClass::style(), "button" => false));
	}

	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if (empty($lists)) {
			exit('参数错误');
		} else {
			$listId = base64_decode($lists, true);
			$array  = explode(',', $listId);
			$data   = [];
			foreach ($array as $id) {
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                  = $param ?: $this->get('id');
		$info                = query(self::table, " id = '$id'");
		$info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
		$info['title']       = self::title;
		$info['printTime']   = $this->time;
		$info['stid']        = self::findStaff($info['stid']);
		$info['sorderNo']    = $info['sourceTable'] ? query($info['sourceTable'], " id = '{$info['sourceId']}' ")['orderNo'] : '';
		$info['warehouseId'] = warehouseClass::getName($info['warehouseId']);
		$info['targetId']    = inStockOtherClass::getCompanyName($info['targetId']);
		$info['qr']          = 'source=' . self::page . 'Other&id=' . $info['id'];
		$info['orderDate']   = date('Y/m/d', strtotime($info['orderDate']) ?: strtotime($info['time']));
		$detail              = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
		$items               = [];
		$x                   = 1;
		$totalNum            = 0;
		foreach ($detail as $array) {
			$material    = query('material', "id = '$array[materialId]'");
			$items[]     = [
				'no'              => $x,
				'materialCode'    => $material['code'],
				'materialName'    => $material['name'],
				'warehouse'       => warehouseClass::getName($array['warehouseId']),
				'model'           => $material['model'],
				'unit'            => $material['unit'],
				'num'             => self::lostZero($array['num'], 'numPrecision'),
				'text'            => $array['text'],
			];
			$x++;
			$totalNum += $array['num'];
		}
		$append         = [
			'no'  => L('outStock.printPage.total'),
			'num' => self::lostZero($totalNum, 'numPrecision'),
		];
		$items[]        = $append;
		$info['detail'] = $items;
		if ($isReturn) {
			return (new printTemplateClass())->start(self::page, $info);
		} else {
			return $info;
		}
	}

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'仓库',
                    'aliasName'=>'仓库',
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                ],
                [
                    'columnName'=>'源单编号',
                    'aliasName'=>'源单编号',
                ],
                [
                    'columnName'=>'往来单位',
                    'aliasName'=>'往来单位',
                ],
                [
                    'columnName'=>'源单日期',
                    'aliasName'=>'源单日期',
                ],
                [
                    'columnName'=>'出库单号',
                    'aliasName'=>'出库单号',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'单据数量',
                    'aliasName'=>'单据数量',
                ],
                [
                    'columnName'=>'已出库数量',
                    'aliasName'=>'已出库数量',
                ],
                [
                    'columnName'=>'批次明细',
                    'aliasName'=>'批次明细',
                ],
                [
                    'columnName'=>'剩余未出库数量',
                    'aliasName'=>'剩余未出库数量',
                ],
            ]
        };
    }
}
